

package com.hd2tecnologia.telas;

import com.hd2tecnologia.entidades.Usuario;
import com.hd2tecnologia.mensagens.LogErros;
import com.hd2tecnologia.modeloBanco.UsuarioBD;
import com.hd2tecnologia.utilidades.Icones;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Dulcyelliton Silva
 */
public class UsuarioTela extends javax.swing.JFrame {
   
    
    private DefaultTableModel tableModel;
    private ListSelectionModel listModel;
    private List<Usuario> usuarios;
    private static UsuarioTela instance; //Utilizada para auxiliar na instancia do formulário
    
    Icones icone = new Icones();
    
    public UsuarioTela() {
        try {
            initComponents();
            defineModelo();
            atualizaTabela();
        } catch (SQLException ex) {
            Logger.getLogger(UsuarioTela.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

     
    
     private void defineModelo(){
        //O TABLEMODEL é utilizado para definir os dados da minha tabela tabela!
        tableModel = (DefaultTableModel) tbl_Usuarios.getModel();
        //O  utilizado para escutar os eventos da minha tabela!
        listModel = tbl_Usuarios.getSelectionModel();
        listModel.addListSelectionListener(new ListSelectionListener(){
           
            public void valueChanged(ListSelectionEvent e){
                if(!e.getValueIsAdjusting()){
                   mostraDetalheUsuario();
                }
            }
        });
    }
     
     private void mostraDetalheUsuario() {
        if (tbl_Usuarios.getSelectedRow() != -1) {
            int indice = tbl_Usuarios.getSelectedRow();
            txt_NomeUsuario.setText(usuarios.get(indice).getNome());
            btn_EditarUsuario.setEnabled(true);
            btn_ExcluirUsuario.setEnabled(true);
            String auxTipo;
            if(usuarios.get(indice).getTipo()==2){
                auxTipo = "Usuario";
            }else{
                auxTipo = "Administrador";
            }
            cbb_TipoUsuario.setSelectedItem(auxTipo);
            txt_TelefoneUsuario.setText(usuarios.get(indice).getTelefone());
            txt_EmailUsuario.setText(usuarios.get(indice).getEmail());
            txt_LoginUsuario.setText(usuarios.get(indice).getLogin());
            txt_SenhaUsuario.setText(usuarios.get(indice).getSenha());
        } else {
            txt_NomeUsuario.setText("");
            cbb_TipoUsuario.setSelectedItem("Selecione");
            txt_EmailUsuario.setText("");
            txt_TelefoneUsuario.setText("");
            txt_LoginUsuario.setText("");
            txt_SenhaUsuario.setText("");
        }
    }
     
     
    public void atualizaTabela() throws SQLException {

        UsuarioBD ModeloCliente = UsuarioBD.getInstance();
        System.out.println(txt_PesquisaUsuarioNome.getText());
        
        if( txt_PesquisaUsuarioNome.getText().isEmpty() ){
            usuarios = ModeloCliente.consultaUsuario();
        }else{
            String nome = txt_PesquisaUsuarioNome.getText();
            usuarios = ModeloCliente.consultaUsuario(nome);   
        }
        
        //Util util = new Util();
        
        int numeroLinhas = tableModel.getRowCount();
        for (int i = 0; i < numeroLinhas; i++) {
            tableModel.removeRow(0);
        }
        for (int i = 0; i < usuarios.size(); i++) {
            String auxTipo = null;
            if(usuarios.get(i).getTipo()==1){
                auxTipo = "Administrador";
            }else{
                if(usuarios.get(i).getTipo()==2){
                    auxTipo = "Usuário";
                }
            }
            tableModel.insertRow(i, new Object[]{usuarios.get(i).getId(), usuarios.get(i).getNome(), auxTipo});
        }         
    }
     
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txt_NomeUsuario = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txt_EmailUsuario = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        cbb_TipoUsuario = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        txt_TelefoneUsuario = new javax.swing.JFormattedTextField();
        jLabel6 = new javax.swing.JLabel();
        txt_LoginUsuario = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txt_SenhaUsuario = new javax.swing.JPasswordField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbl_Usuarios = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        btn_NovoUsuario = new javax.swing.JButton();
        btn_InserirUsuario = new javax.swing.JButton();
        btn_EditarUsuario = new javax.swing.JButton();
        btn_SalvarEdicaoUsuario = new javax.swing.JButton();
        btn_ExcluirUsuario = new javax.swing.JButton();
        btn_CancelarEVoltar = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        txt_PesquisaUsuarioNome = new javax.swing.JTextField();
        btn_BuscarUsuario = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("[USUARIO] - DSControl - Sistema de Gestão de Comércio");
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(51, 51, 255));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Cadastro de Usuários");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados do Usuário"));

        jLabel2.setText("Nome:*");

        txt_NomeUsuario.setEnabled(false);

        jLabel3.setText("E-mail:");

        txt_EmailUsuario.setEnabled(false);

        jLabel4.setText("Tipo:*");

        cbb_TipoUsuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione", "Usuario", "Administrador" }));
        cbb_TipoUsuario.setEnabled(false);
        cbb_TipoUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbb_TipoUsuarioActionPerformed(evt);
            }
        });

        jLabel5.setText("Telefone:");

        try {
            txt_TelefoneUsuario.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txt_TelefoneUsuario.setEnabled(false);

        jLabel6.setText("Login:*");

        txt_LoginUsuario.setEnabled(false);

        jLabel7.setText("Senha:*");

        txt_SenhaUsuario.setToolTipText("Mínimo de 4 Máximo de 10");
        txt_SenhaUsuario.setEnabled(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txt_NomeUsuario)
                    .addComponent(txt_EmailUsuario)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(cbb_TipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txt_TelefoneUsuario))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(txt_LoginUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel7)
                        .addGap(18, 18, 18)
                        .addComponent(txt_SenhaUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {txt_LoginUsuario, txt_SenhaUsuario});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txt_NomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cbb_TipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txt_TelefoneUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txt_EmailUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txt_LoginUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txt_SenhaUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {cbb_TipoUsuario, txt_EmailUsuario, txt_LoginUsuario, txt_NomeUsuario, txt_SenhaUsuario, txt_TelefoneUsuario});

        tbl_Usuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID/Número", "Nome", "Tipo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tbl_Usuarios);
        tbl_Usuarios.getColumnModel().getColumn(0).setMinWidth(70);
        tbl_Usuarios.getColumnModel().getColumn(0).setMaxWidth(70);
        tbl_Usuarios.getColumnModel().getColumn(2).setMinWidth(150);
        tbl_Usuarios.getColumnModel().getColumn(2).setMaxWidth(150);

        jPanel3.setLayout(new java.awt.GridLayout(1, 6, 2, 2));

        btn_NovoUsuario.setText("Novo");
        btn_NovoUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_NovoUsuarioActionPerformed(evt);
            }
        });
        jPanel3.add(btn_NovoUsuario);

        btn_InserirUsuario.setText("Inserir");
        btn_InserirUsuario.setEnabled(false);
        btn_InserirUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_InserirUsuarioActionPerformed(evt);
            }
        });
        jPanel3.add(btn_InserirUsuario);

        btn_EditarUsuario.setText("Editar");
        btn_EditarUsuario.setEnabled(false);
        btn_EditarUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_EditarUsuarioActionPerformed(evt);
            }
        });
        jPanel3.add(btn_EditarUsuario);

        btn_SalvarEdicaoUsuario.setText("Salvar");
        btn_SalvarEdicaoUsuario.setEnabled(false);
        btn_SalvarEdicaoUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_SalvarEdicaoUsuarioActionPerformed(evt);
            }
        });
        jPanel3.add(btn_SalvarEdicaoUsuario);

        btn_ExcluirUsuario.setText("Excluir");
        btn_ExcluirUsuario.setEnabled(false);
        btn_ExcluirUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ExcluirUsuarioActionPerformed(evt);
            }
        });
        jPanel3.add(btn_ExcluirUsuario);

        btn_CancelarEVoltar.setText("Cancelar");
        btn_CancelarEVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_CancelarEVoltarActionPerformed(evt);
            }
        });
        jPanel3.add(btn_CancelarEVoltar);

        jLabel8.setText("Filtro por nome:");

        btn_BuscarUsuario.setText("Buscar");
        btn_BuscarUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_BuscarUsuarioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txt_PesquisaUsuarioNome, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_BuscarUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jScrollPane2)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txt_PesquisaUsuarioNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_BuscarUsuario))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-496)/2, (screenSize.height-487)/2, 496, 487);
    }// </editor-fold>//GEN-END:initComponents

    private void btn_CancelarEVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_CancelarEVoltarActionPerformed
        btn_InserirUsuario.setEnabled(false);
        btn_EditarUsuario.setEnabled(false);
        btn_ExcluirUsuario.setEnabled(false);
        btn_SalvarEdicaoUsuario.setEnabled(false);
        tbl_Usuarios.setEnabled(true);
        desabilitarCampos();
        limparCampos();
        this.dispose();
    }//GEN-LAST:event_btn_CancelarEVoltarActionPerformed

    private void btn_NovoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_NovoUsuarioActionPerformed
        try {
            limparCampos();
            habilitarCampos();
            atualizaTabela();
            tbl_Usuarios.setEnabled(false);
            btn_InserirUsuario.setEnabled(true);
            btn_EditarUsuario.setEnabled(false);
            btn_ExcluirUsuario.setEnabled(false);
            btn_SalvarEdicaoUsuario.setEnabled(false);
        } catch (SQLException ex) {
            Logger.getLogger(UsuarioTela.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btn_NovoUsuarioActionPerformed

    private void btn_InserirUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_InserirUsuarioActionPerformed
         if (txt_NomeUsuario.getText().trim().equals("") || cbb_TipoUsuario.getSelectedItem().toString().equals("Selecione") 
                || txt_LoginUsuario.getText().trim().equals("") || txt_SenhaUsuario.getPassword().length == 0) {
            JOptionPane.showMessageDialog(this, "Os Campos com * são obrigatórios!", "Erro", JOptionPane.ERROR_MESSAGE);
            
            // 01 -- Parte do código utilizado para verificar qual o campo obrigatório está faltando ser preenchido
            if(txt_NomeUsuario.getText().trim().equals("")){
                txt_NomeUsuario.requestFocus();
            }else{
                if(cbb_TipoUsuario.getSelectedItem().toString().equals("Selecione")){
                    cbb_TipoUsuario.requestFocus();
                }else{
                    if(txt_LoginUsuario.getText().trim().equals("")){
                        txt_LoginUsuario.requestFocus();                        
                    }else{
                        txt_SenhaUsuario.requestFocus();
                    }
                }
            }// 01 -- Parte do código utilizado para verificar qual o campo obrigatório está faltando ser preenchido
            
         }else{
            try {
                incluirUsuario();
            } catch (SQLException ex) {
                Logger.getLogger(UsuarioTela.class.getName()).log(Level.SEVERE, null, ex);
            }
          }
    }//GEN-LAST:event_btn_InserirUsuarioActionPerformed

    private void btn_BuscarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_BuscarUsuarioActionPerformed
        try {
            btn_EditarUsuario.setEnabled(false);
            btn_SalvarEdicaoUsuario.setEnabled(false);
            btn_ExcluirUsuario.setEnabled(false);
            btn_InserirUsuario.setEnabled(false);
            tbl_Usuarios.setEnabled(true);
            limparCampos();
            desabilitarCampos();
            atualizaTabela();
        } catch (SQLException ex) {
            Logger.getLogger(UsuarioTela.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btn_BuscarUsuarioActionPerformed

    private void btn_EditarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_EditarUsuarioActionPerformed
      habilitarCampos();
      tbl_Usuarios.setEnabled(false);
      btn_SalvarEdicaoUsuario.setEnabled(true);
    }//GEN-LAST:event_btn_EditarUsuarioActionPerformed

    private void btn_ExcluirUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ExcluirUsuarioActionPerformed
        if(tbl_Usuarios.getSelectedRow() == 0){
            JOptionPane.showMessageDialog(null, "Não pode excluir, pois apenas existe um usuário cadastrado!");
        }else{
        int permissao = JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir o usuário selecionado?", "Confirmação de Exclusão", JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION, icone.getLIXO());
     
     if(permissao == 0){
     UsuarioBD usuarioBD = UsuarioBD.getInstance();
     LogErros log = LogErros.getInstance();
        try {
            if (tbl_Usuarios.getSelectedRow() != -1) {
                int indice = tbl_Usuarios.getSelectedRow();
                usuarioBD.excluiUsuario(usuarios.get(indice));
                JOptionPane.showMessageDialog(null, "Usuário "+usuarios.get(indice).getNome() +" exclúido com Sucesso!", "Confirmação de Exclusão", JOptionPane.WARNING_MESSAGE, icone.getLIXO());
                atualizaTabela();
             }
        } catch (SQLException ex) {
            Logger.getLogger(UsuarioTela.class.getName()).log(Level.SEVERE, null, ex);
        }
     }
    }
    }//GEN-LAST:event_btn_ExcluirUsuarioActionPerformed

    private void cbb_TipoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbb_TipoUsuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbb_TipoUsuarioActionPerformed

    private void btn_SalvarEdicaoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_SalvarEdicaoUsuarioActionPerformed
        if (txt_NomeUsuario.getText().trim().equals("") || cbb_TipoUsuario.getSelectedItem().toString().equals("Selecione") 
                || txt_LoginUsuario.getText().trim().equals("") || txt_SenhaUsuario.getPassword().length == 0) {
            JOptionPane.showMessageDialog(this, "Os Campos com * são obrigatórios!", "Erro", JOptionPane.ERROR_MESSAGE);
            
            // 01 -- Parte do código utilizado para verificar qual o campo obrigatório está faltando ser preenchido
            if(txt_NomeUsuario.getText().trim().equals("")){
                txt_NomeUsuario.requestFocus();
            }else{
                if(cbb_TipoUsuario.getSelectedItem().toString().equals("Selecione")){
                    cbb_TipoUsuario.requestFocus();
                }else{
                    if(txt_LoginUsuario.getText().trim().equals("")){
                        txt_LoginUsuario.requestFocus();                        
                    }else{
                        txt_SenhaUsuario.requestFocus();
                    }
                }
            }// 01 -- Parte do código utilizado para verificar qual o campo obrigatório está faltando ser preenchido
            
         }else{
            try {
                alterarUsuario();
            } catch (SQLException ex) {
                Logger.getLogger(UsuarioTela.class.getName()).log(Level.SEVERE, null, ex);
            }
          }
    }//GEN-LAST:event_btn_SalvarEdicaoUsuarioActionPerformed

   
    public void alterarUsuario() throws SQLException{
              
        Usuario usuario = Usuario.getInstance();
      if (tbl_Usuarios.getSelectedRow() != -1) {
        int indice = tbl_Usuarios.getSelectedRow();  
       
        usuario.setNome(usuarios.get(indice).getNome());
        usuario.setEmail(usuarios.get(indice).getEmail());
        usuario.setTelefone(usuarios.get(indice).getTelefone());
        usuario.setTipo(usuarios.get(indice).getTipo());
        usuario.setLogin(usuarios.get(indice).getLogin());
        usuario.setSenha(usuarios.get(indice).getSenha());
        usuario.setId(usuarios.get(indice).getId());
        /*Para setar a senha do usupario, estou convertendo o JPasswordField que é um array de char para tipo String*/
      }
       boolean aux;
        UsuarioBD usuarioBD = new UsuarioBD();
        aux = usuarioBD.alterarUsuario(usuario);
        if(aux){
            limparCampos();
            desabilitarCampos();
            atualizaTabela();
            btn_InserirUsuario.setEnabled(false);
            JOptionPane.showMessageDialog(null, "Usuário alterado com sucesso!");
        }else{
            limparCampos();
            desabilitarCampos();
            JOptionPane.showMessageDialog(null, "Erro ao alterar o usuário! Tente novamente.");
        } 
 }
    
    public void incluirUsuario() throws SQLException{
        Usuario usuario = Usuario.getInstance();
       
        usuario.setNome(txt_NomeUsuario.getText());
        usuario.setEmail(txt_EmailUsuario.getText());
        usuario.setTelefone(txt_TelefoneUsuario.getText());
        if(cbb_TipoUsuario.getSelectedItem()=="Administrador"){
            usuario.setTipo(1);
        }else if(cbb_TipoUsuario.getSelectedItem()=="Usuario"){
            usuario.setTipo(2);
        }
        usuario.setLogin(txt_LoginUsuario.getText());
        usuario.setSenha(String.copyValueOf(txt_SenhaUsuario.getPassword()));
        /*Para setar a senha do usupario, estou convertendo o JPasswordField que é um array de char para tipo String*/
        
        UsuarioBD usuarioBD = new UsuarioBD();
        boolean aux;
        aux = usuarioBD.incluiUsuario(usuario);
        if(aux==true){
            limparCampos();
            desabilitarCampos();
            atualizaTabela();
            btn_InserirUsuario.setEnabled(false);
            JOptionPane.showMessageDialog(null, "Usuário cadastrado com sucesso!");
        }else{
            limparCampos();
            desabilitarCampos();
            JOptionPane.showMessageDialog(null, "Erro ao cadastrar o usuário! Tente novamente.");
        }
    }
    
    
    public void habilitarCampos(){
        txt_NomeUsuario.setEnabled(true);
        txt_EmailUsuario.setEnabled(true);
        cbb_TipoUsuario.setEnabled(true);
        txt_TelefoneUsuario.setEnabled(true);
        txt_LoginUsuario.setEnabled(true);
        txt_SenhaUsuario.setEnabled(true);
    }
    
    public void desabilitarCampos(){
        txt_NomeUsuario.setEnabled(false);
        txt_EmailUsuario.setEnabled(false);
        cbb_TipoUsuario.setEnabled(false);
        txt_TelefoneUsuario.setEnabled(false);
        txt_LoginUsuario.setEnabled(false);
        txt_SenhaUsuario.setEnabled(false);
    }
    
    public void limparCampos(){
        txt_NomeUsuario.setText("");
        txt_EmailUsuario.setText("");
        cbb_TipoUsuario.setSelectedItem("Selecione");
        txt_TelefoneUsuario.setText("");
        txt_LoginUsuario.setText("");
        txt_SenhaUsuario.setText("");
    }
    
    /*
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new UsuarioTela().setVisible(true);
            }
        });
    }*/
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_BuscarUsuario;
    private javax.swing.JButton btn_CancelarEVoltar;
    private javax.swing.JButton btn_EditarUsuario;
    private javax.swing.JButton btn_ExcluirUsuario;
    private javax.swing.JButton btn_InserirUsuario;
    private javax.swing.JButton btn_NovoUsuario;
    private javax.swing.JButton btn_SalvarEdicaoUsuario;
    private javax.swing.JComboBox cbb_TipoUsuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable tbl_Usuarios;
    private javax.swing.JTextField txt_EmailUsuario;
    private javax.swing.JTextField txt_LoginUsuario;
    private javax.swing.JTextField txt_NomeUsuario;
    private javax.swing.JTextField txt_PesquisaUsuarioNome;
    private javax.swing.JPasswordField txt_SenhaUsuario;
    private javax.swing.JFormattedTextField txt_TelefoneUsuario;
    // End of variables declaration//GEN-END:variables


public static UsuarioTela getInstance(){
    if(instance==null){
        instance = new UsuarioTela();
    }
    return instance;
}

public static void kilInstance(){
    instance = null;
}
    

}
